package com.leo.groupchat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author du
 */
public class GroupChatClient {

    private final int PORT = 6667;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    private CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
    private CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();


    public GroupChatClient() {
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open(/*new InetSocketAddress("127.0.0.1", PORT)*/);
            socketChannel.connect(new InetSocketAddress("127.0.0.1", PORT));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            username = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println(username + " is ok...");

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void doSend() {
        //BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
        Scanner scanner = new Scanner(System.in);
        try {
            String readline;
            while(/*(readline = sin.readLine()) != null*/
                    scanner.hasNextLine()) {
                readline = scanner.nextLine().trim();
                if (readline.equals("bye")) {
                    selector.close();
                    socketChannel.close();
                }
                String msg = username + "说: " + readline.trim();
                socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
                //socketChannel.write(encoder.encode(CharBuffer.wrap(msg)));
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public void doRead() {

        new Thread(() -> {
            try {
                while (true) {
                    if(selector.select(2000) == 0) {
                        continue;
                    }
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();

                        if (key.isConnectable()) {
                            SocketChannel channel = (SocketChannel) key.channel();
                            if (channel.isConnectionPending()) { //肯定是true
                                channel.finishConnect();
                            }
                            channel.register(selector, SelectionKey.OP_READ);
                            System.out.println("连接服务器成功!");
                        }

                        if (key.isReadable()) {
                            SocketChannel channel = (SocketChannel) key.channel();
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            CharBuffer charBuffer = CharBuffer.allocate(1024);
                            int read;
                            String msg = "";
                            while((read = channel.read(buffer)) > 0) {
                                msg += new String(buffer.array(), 0, read);
                                //msg += decoder.decode(buffer, charBuffer, true).toString();
                                buffer.clear();//此处必须重置, 否则下一次read的索引位置会错乱
                            }
                            System.out.println(msg);
                        }
                    }
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }).start();
    }


    public static void main(String[] args) {
        GroupChatClient client = new GroupChatClient();
        client.doRead();
        client.doSend();
    }
}
